﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.IO;

namespace MassTest
{
	public enum ECharModel
	{
		assassin001,
		cleric001,
		dukakidigger001,
		dukakiminer001,
		dukakipatrol001,
		haskin001,
		kuntura001,
		paruka001,
		sorcerer001,
		spiritmaster001,
		takata001,
		templar001,

		assassin002,
		cleric002,
		dukakidigger002,
		dukakiminer002,
		dukakipatrol002,
		haskin002,
		kuntura002,
		paruka002,
		sorcerer002,
		spiritmaster002,
		takata002,
		templar002,

		assassin003,
		cleric003,
		dukakidigger003,
		dukakiminer003,
		dukakipatrol003,
		haskin003,
		kuntura003,
		paruka003,
		sorcerer003,
		spiritmaster003,
		takata003,
		templar003,

		assassin004,
		cleric004,
		dukakidigger004,
		dukakiminer004,
		dukakipatrol004,
		haskin004,
		kuntura004,
		paruka004,
		sorcerer004,
		spiritmaster004,
		takata004,
		templar004,
	}
}

public class UIDeployPanel : MonoBehaviour {

	private static UIDeployPanel instance;
	
	public static UIDeployPanel Instance{
		get{
			return instance;
		}
	}	
	
	void Awake()
	{
		instance = this;
		if(UserData.Instance.userModel==null)
			isActive=true;
	}
	public static bool isActive;
	Vector3 topLeftPos = new Vector3(-358, 182, 0);
	float gap_x = 49;
	float gap_y = 45;
	public GameObject panel;
	GameObject charToDeployPrefab;
	List<UICharToDeploy> charToDeployList = new List<UICharToDeploy>();
	List<ECharModel> meleeModels = new List<ECharModel>();

	void Start()
	{
		//SetDeployPanel();
		if(UserData.Instance.userModel!=null) {
			if(panel!=null)
				panel.SetActive(false);
			isActive=false;
		}
	}

	public void SetDeployPanel_Old()
	{
		List<ECharModel> candidateCharModels = new List<ECharModel>();
		for(int i=0; i<6; i++) {
			foreach (ECharModel charModel in Enum.GetValues(typeof(ECharModel)))
			{
				if(charModel == ECharModel.Assassin || charModel== ECharModel.Cleric || charModel == ECharModel.Sorcerer || charModel== ECharModel.Spiritmaster || charModel== ECharModel.Templar)
				{
					candidateCharModels.Add (charModel);
					string strCharModel = charModel.ToString();
					//if(strCharModel.StartsWith("assassin") || strCharModel.StartsWith("templar") || strCharModel.StartsWith("dukakidigger") 
					//   || strCharModel.StartsWith("dukakipatrol") || strCharModel.StartsWith("kuntura") || strCharModel.StartsWith("paruka") || strCharModel.StartsWith("takata") )
					if(strCharModel.StartsWith("Assassin") || strCharModel.StartsWith("Templar") || strCharModel.StartsWith("Cleric")) {
						if( !meleeModels.Contains(charModel) )
							meleeModels.Add(charModel);
					}
				}
			}
		}
		charToDeployPrefab = Resources.Load("Prefab/Battle/Test/UICharToDeploy") as GameObject;
		int nCharModelIndex = 0;
		for(int i=0; i<30; i++) {
			GameObject go = Instantiate( charToDeployPrefab ) as GameObject;
			if(nCharModelIndex==candidateCharModels.Count)
				nCharModelIndex=0;
			UICharToDeploy charToDeploy = go.GetComponent<UICharToDeploy>();
			charToDeploy.charModel = candidateCharModels[nCharModelIndex];
			charToDeploy.mNo = i+1;
			charToDeployList.Add(charToDeploy);
			string jobName = candidateCharModels[nCharModelIndex].ToString();
			if(jobName.StartsWith("dukaki"))
				jobName = jobName.Substring(6,4);
			else
				jobName = jobName.Substring(0,4);
			go.transform.FindChild("JobLabel").GetComponent<UILabel>().text = jobName;
			go.transform.parent = panel.transform;
			Vector3 newPos = topLeftPos;
			int nRow = (int)(i / 6);
			int nCol = i % 6;
			newPos.x += nCol * gap_x;
			newPos.y -= nRow * gap_y;
			go.transform.localPosition = newPos;
			go.transform.localRotation = Quaternion.identity;
			go.transform.localScale = Vector3.one;
			nCharModelIndex++;
		}
	}

	ECharModel CheckCharModel(int classId)
	{
		if(classId==18)
			return ECharModel.Assassin;
		else if(classId==16)
			return ECharModel.Templar;
		else if(classId==19)
			return ECharModel.Sorcerer;
		else if(classId==20)
			return ECharModel.Spiritmaster;
		else if(classId==14 || classId==22)
			return ECharModel.Cleric;
		return ECharModel.Assassin;
	}

	public void SetDeployPanel_Old2()
	{
		List<ECharModel> candidateCharModels = new List<ECharModel>();
		List<int> candidateClassIds = new List<int>();
		List<int> candidateNos = new List<int>();
		foreach( var pair in UserData.Instance.userModel.members_dic) {
			MemberModel memmodel = pair.Value;
			ECharModel charModel = ECharModel.Assassin;
			int classId = 0;
			bool classDetermined=false;
			for(int i=0 ;i< memmodel.traits.Length; i++) 
			{
				if( memmodel.traits[i] >=11 && memmodel.traits[i]<=22) {
					classId = memmodel.traits[i];
					charModel = CheckCharModel(classId);
					candidateCharModels.Add (charModel);
					candidateClassIds.Add(classId);
					candidateNos.Add (memmodel.no);
					string strCharModel = charModel.ToString();
					if(strCharModel.StartsWith("Assassin") || strCharModel.StartsWith("Templar") || strCharModel.StartsWith("Cleric")) {
						if( !meleeModels.Contains(charModel) )
							meleeModels.Add(charModel);
					}
					classDetermined=true;
					break;
				}
			}
			if(!classDetermined) {
				classId = 0;
				charModel = BattleResManager.FindCharModel(memmodel.model);
				candidateCharModels.Add (charModel);
				candidateClassIds.Add(classId);
				candidateNos.Add (memmodel.no);
				string strCharModel = charModel.ToString();
				if(!strCharModel.StartsWith("Dukakiminer") && !strCharModel.StartsWith("Haskin") ) {
					if( !meleeModels.Contains(charModel) )
						meleeModels.Add(charModel);
				}
			}
		}


		charToDeployPrefab = Resources.Load("Prefab/Battle/Test/UICharToDeploy") as GameObject;
		int nCharModelIndex = 0;
		for(int i=0; i<30; i++) {
			GameObject go = Instantiate( charToDeployPrefab ) as GameObject;
			if(nCharModelIndex==candidateCharModels.Count)
				nCharModelIndex=0;
			UICharToDeploy charToDeploy = go.GetComponent<UICharToDeploy>();
			charToDeploy.charModel = candidateCharModels[nCharModelIndex];
			charToDeploy.mNo = i+1;
			charToDeploy.memmodelNo = candidateNos[nCharModelIndex];
			charToDeployList.Add(charToDeploy);
			string jobName = candidateClassIds[nCharModelIndex].ToString();
			go.transform.FindChild("JobLabel").GetComponent<UILabel>().text = jobName;
			go.transform.parent = panel.transform;
			Vector3 newPos = topLeftPos;
			int nRow = (int)(i / 6);
			int nCol = i % 6;
			newPos.x += nCol * gap_x;
			newPos.y -= nRow * gap_y;
			go.transform.localPosition = newPos;
			go.transform.localRotation = Quaternion.identity;
			go.transform.localScale = Vector3.one;
			nCharModelIndex++;
		}
	}

	List<MemberModel> modelList; 
	List<MemberModel> toDeleteMem;

	void DeleteInvaidMember()
	{
		toDeleteMem = new List<MemberModel>();
		foreach( MemberModel memmodel in modelList) {
			bool checkOk=false;
			foreach(DStartChar dchar in GameData.Inst.startChar){
				if(memmodel.model == dchar.charModel) {
					checkOk=true;
					break;
				}
			}
			if(!checkOk) {
				Debug.LogError(" delete invalid model not in start char  modelid="+memmodel.model);
				toDeleteMem.Add (memmodel);
			}
		}
	}

	public void SetDeployPanel()
	{
		List<ECharModel> candidateCharModels = new List<ECharModel>();
		List<int> candidateClassIds = new List<int>();
		List<int> candidateNos = new List<int>();
		List<int> candidateModelIds = new List<int>();

		modelList = new List<MemberModel>();

		foreach( var pair in UserData.Instance.userModel.members_dic) {
			MemberModel memmodel = pair.Value;
			modelList.Add(memmodel);
		}

		Debug.Log("modelList.count = "+modelList.Count);

		DeleteInvaidMember();

		List<MemberModel> finalmodelList = new List<MemberModel>(); 
		foreach( MemberModel memmodel in modelList) {
			if( !toDeleteMem.Contains(memmodel))
				finalmodelList.Add(memmodel);
		}

		Debug.Log ("finalmodelList.Count="+finalmodelList.Count);

		while(finalmodelList.Count>30) {
			int nIndex= UnityEngine.Random.Range(0, finalmodelList.Count);
			finalmodelList.RemoveAt(nIndex);
		}

		foreach( MemberModel memmodel in finalmodelList) {
			ECharModel charModel = ECharModel.Assassin;
			int classId = 0;
			bool classDetermined=false;
			for(int i=0 ;i< memmodel.traits.Length; i++) 
			{
				if( memmodel.traits[i] >=11 && memmodel.traits[i]<=22) {
					classId = memmodel.traits[i];
					charModel = CheckCharModel(classId);
					candidateCharModels.Add (charModel);
					candidateClassIds.Add(classId);
					candidateNos.Add (memmodel.no);
					candidateModelIds.Add(memmodel.model);
					string strCharModel = charModel.ToString();
					if(strCharModel.StartsWith("Assassin") || strCharModel.StartsWith("Templar") || strCharModel.StartsWith("Cleric")) {
						if( !meleeModels.Contains(charModel) )
							meleeModels.Add(charModel);
					}
					classDetermined=true;
					break;
				}
			}
			if(!classDetermined) {
				classId = 0;
				charModel = BattleResManager.FindCharModel(memmodel.model);
				candidateCharModels.Add (charModel);
				candidateClassIds.Add(classId);
				candidateNos.Add (memmodel.no);
				candidateModelIds.Add(memmodel.model);
				string strCharModel = charModel.ToString();
				if(!strCharModel.StartsWith("Dukakiminer") && !strCharModel.StartsWith("Haskin") ) {
					if( !meleeModels.Contains(charModel) )
						meleeModels.Add(charModel);
				}
			}
		}
		
		//GameObject uiCharparent = new GameObject();
		//uiCharparent.name = "uiCharParent";
		charToDeployPrefab = Resources.Load("Prefab/Battle/Test/UICharToDeploy") as GameObject;
		int nCharModelIndex = 0;
		for(int i=0; i<30; i++) {
			GameObject go = Instantiate( charToDeployPrefab ) as GameObject;
			if(nCharModelIndex==candidateCharModels.Count)
				nCharModelIndex=0;
			UICharToDeploy charToDeploy = go.GetComponent<UICharToDeploy>();
			charToDeploy.charModel = candidateCharModels[nCharModelIndex];
			charToDeploy.mNo = i+1;
			charToDeploy.memmodelNo = candidateNos[nCharModelIndex];
			charToDeploy.modelId = candidateModelIds[nCharModelIndex];
			charToDeployList.Add(charToDeploy);
			//go.transform.parent = uiCharparent.transform;
//			string jobName = candidateClassIds[nCharModelIndex].ToString();
//			go.transform.FindChild("JobLabel").GetComponent<UILabel>().text = jobName;
//			go.transform.parent = panel.transform;
//			Vector3 newPos = topLeftPos;
//			int nRow = (int)(i / 6);
//			int nCol = i % 6;
//			newPos.x += nCol * gap_x;
//			newPos.y -= nRow * gap_y;
//			go.transform.localPosition = newPos;
//			go.transform.localRotation = Quaternion.identity;
//			go.transform.localScale = Vector3.one;
			nCharModelIndex++;
		}
	}

	public UICharToDeploy FindUIChar(int memberNo)
	{
		foreach(UICharToDeploy uiChar in charToDeployList) {
			if(uiChar.mNo == memberNo)
				return uiChar;
		}
		return null;
	}

	void OnAutoClick()
	{
		if(ArmyDeploy.isDeploying) return;
		ArmyDeploy.isDeploying=true;
		ArmyDeploy.Instance.UnDeployAll();
		//StartCoroutine("CoAutoDeploy");
		CoAutoDeploy();
	}

	public void AutoDeployEnemy()
	{
		ArmyDeploy.isDeployingEnemy=true;
		//StartCoroutine("CoAutoDeploy");
		CoAutoDeploy();
	}

	public void AutoDeployNew()
	{
		ArmyDeploy.isDeploying=true;
		//StartCoroutine("CoAutoDeploy");
		ArmyDeploy.Instance.CalcDeployPosition();
		CoAutoDeploy();
	}

	void CoAutoDeploy()
	{
		//if(charToDeployList.Count<30) {
		//	Debug.LogError(" characters should be 30 ");
		//	yield break;
		//}
		List<UICharToDeploy> deployList = new List<UICharToDeploy>();
		List<UICharToDeploy> meleeChars = new List<UICharToDeploy>();
		List<UICharToDeploy> rangeChars = new List<UICharToDeploy>();
		//List<ECharModel> meleeModels = new List<ECharModel> {ECharModel.Assassin, ECharModel.Templar, ECharModel.Dukakidigger, ECharModel.Dukakipatrol, ECharModel.Kuntura, ECharModel.Paruka, ECharModel.Takata};

		foreach(UICharToDeploy uiChar in charToDeployList) {
			if( meleeModels.Contains(uiChar.charModel) )
				meleeChars.Add( uiChar);
			else
				rangeChars.Add(uiChar);
		}
		Debug.Log("melee="+meleeChars.Count+"  range="+rangeChars.Count);
		
		while(meleeChars.Count< ArmyDeploy.Instance.lineMax[0])//밀리계열이 부족하면 레인지 계열로 채워넣는다
		{
			if(rangeChars.Count==0)
				break;
			int nIndex = UnityEngine.Random.Range(0, rangeChars.Count);
			meleeChars.Add ( rangeChars[nIndex]);
			rangeChars.RemoveAt(nIndex);
		}
		
		while(deployList.Count< ArmyDeploy.Instance.lineMax[0])//밀리 계열 앞줄에 배치
		{
			if(meleeChars.Count==0)
				break;
			int nIndex = UnityEngine.Random.Range(0, meleeChars.Count);
			deployList.Add ( meleeChars[nIndex]);
			meleeChars.RemoveAt(nIndex);
		}
		foreach(UICharToDeploy uiChar in meleeChars)
			rangeChars.Add (uiChar);
		while(deployList.Count< ArmyDeploy.maxDeploy)//레인지 계열 나머지 배치
		{
			if(rangeChars.Count==0)
				break;
			int nIndex = UnityEngine.Random.Range(0, rangeChars.Count);
			deployList.Add ( rangeChars[nIndex]);
			rangeChars.RemoveAt(nIndex);
		}
		foreach(UICharToDeploy uiChar in deployList) {
			uiChar.Deploy();
		}
		ArmyDeploy.isDeploying=false;
		foreach(UICharToDeploy uiChar in charToDeployList) {
			Destroy(uiChar.gameObject);
		}
		isActive=false;
	}

	void OnClearClick()
	{
		ArmyDeploy.Instance.UnDeployAll();
	}

	void OnDelClick()
	{
		 ArmyDeploy.Instance.UnDeploy();
	}

	void OnSave1Click()
	{
		ArmyDeploy.Instance.SaveDeploy(1);
	}

	void OnSave2Click()
	{
		ArmyDeploy.Instance.SaveDeploy(2);
	}

	void OnSave3Click()
	{
		ArmyDeploy.Instance.SaveDeploy(3);
	}

	void OnLoad1Click()
	{
		ArmyDeploy.Instance.LoadDeploy(1);
	}
	
	void OnLoad2Click()
	{
		ArmyDeploy.Instance.LoadDeploy(2);
	}
	
	void OnLoad3Click()
	{
		ArmyDeploy.Instance.LoadDeploy(3);
	}

	void OnStartClick()
	{
		if(ArmyDeploy.isDeploying || !ArmyDeploy.Instance.IsDeployed()) 
			return;
		ArmyDeploy.Instance.OnStart();
		panel.SetActive(false);
		isActive=false;
	}
	
}
